package com.gao.security.verificationcode.common.utils.tree;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *     通用tree组件
 * </p>
 *
 * @author GaoShuangWen
 */
public class TreeUtils {
    /**
     * 将数组转成tree,默认的顶层id,获取方式为实体类的getTopId()
     *
     * @param list
     * @param <T>
     * @return
     */
    public static <T extends ITreeEntity<T>> List<T> listToTree(List<T> list) {
        // 获取最顶级的结果
        List<T> results = new ArrayList<>();
        // 获取顶级元素的id
        list.forEach(tree -> {
            if (tree.getTopId().equals(tree.getPid())) {
                // 顶级元素
                results.add(findChildren(tree, list));
            }
        });
        return results;
    }

    /**
     * 将数组转成tree,自定义顶层id
     *
     * @param topId
     * @param list
     * @param <T>
     * @return
     */
    public static <T extends ITreeEntity<T>> List<T> listToTree(Long topId, List<T> list) {
        // 获取最顶级的结果
        List<T> results = new ArrayList<>();
        // 获取顶级元素的id
        list.forEach(tree -> {
            if (topId.equals(tree.getPid())) {
                // 顶级元素
                results.add(findChildren(tree, list));
            }
        });
        return results;
    }

    /**
     * 递归子节点
     *
     * @param tree
     * @param list
     * @param <T>
     * @return
     */
    private static <T extends ITreeEntity<T>> T findChildren(T tree, List<T> list) {
        list.forEach(t -> {
            if (t.getPid().equals(tree.getId())) {
                if (tree.getChildren() == null) {
                    tree.setChildren(new ArrayList<>());
                }
                tree.getChildren().add(findChildren(t, list));
            }
        });
        return tree;
    }
}
